package com.yonyou.iuap.jxzy.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ch.qos.logback.classic.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.baseservice.intg.service.GenericIntegrateService;
import com.yonyou.iuap.baseservice.intg.support.ServiceFeature;
import com.yonyou.iuap.jxzy.dao.WastePaperBodyMapper;
import com.yonyou.iuap.jxzy.dao.WastePaperHeadMapper;
import com.yonyou.iuap.jxzy.entity.WastePaperBodyVO;
import com.yonyou.iuap.jxzy.entity.WastePaperHeadVO;
import com.yonyou.iuap.jxzy.utils.ExcelParam;
import com.yonyou.uap.ieop.security.exception.BusinessException;

/**
 * 进口废纸service
 * @author wanggp
 * @date 2019年5月28日
 */
@Service
public class WastePaperHeadService extends GenericIntegrateService<WastePaperHeadVO>{

	
	private WastePaperHeadMapper paperheadmapper;
	
	@Autowired
	private WastePaperBodyMapper paperbodymapper;
	
	@Autowired
	private WastePaperBodyService bodyservice;
	
	@Autowired
	public void setPaperheadmapper(WastePaperHeadMapper paperheadmapper){
		 this.paperheadmapper = paperheadmapper;
	     super.setGenericMapper(paperheadmapper);//设置gernericmapper才可以实现分页查询
	}
	
	/**
	 * iuap进口废纸审核
	 * @author wanggp
	 */
	public int verify(List<WastePaperHeadVO> poundlist){
		int length=0;
		if(poundlist!=null && poundlist.size()>0){
			length =this.paperheadmapper.verifypound(poundlist);
		}
		return length;
	}
	
	/**
	 * iuap进口废纸取消审核
	 * @author wanggp
	 * @throws Exception 
	 */
	public int cancelverify(List<String> poundlist) throws Exception{
		int length=0;
		if(poundlist!=null && poundlist.size()>0){
			List<WastePaperHeadVO> pushPoundList=this.paperheadmapper.queryPushPound(poundlist);
			if(pushPoundList!=null && pushPoundList.size()>0){
				throw new Exception("存在已推单的磅单不能取消审核！请检查！");
			}
			length =this.paperheadmapper.cancelverifypound(poundlist);
		}
		return length;
	}
	
	//事务回滚
	@Transactional
	public String  insertPaperHead(WastePaperHeadVO wastepaperhead,List<WastePaperBodyVO> bodylist) throws BusinessException{
		int headlength =0;
		int result=0;
		JSONObject jsonObject=new JSONObject();
		synchronized (wastepaperhead) {
			try {
				if("2".equals(wastepaperhead.getIsCheck())){
					//若这次是提交已检测的，需要先删除待检测
					this.paperheadmapper.deleteWastePaperHeadVO(wastepaperhead);
					this.bodyservice.deletePaperBodyVO(wastepaperhead.getPk_pound());
					//待检测提交的计算
					wastepaperhead =caluImportData(0,wastepaperhead,bodylist);
					if(bodylist!=null && bodylist.size()>0 ){
						result=this.bodyservice.insertPaperBody(bodylist);
						jsonObject.put("message", "新增进口废纸检测主表成功："+headlength+"条，子表成功："+result+"条");
					}
					//重新新增已检测的
					headlength=this.paperheadmapper.insertWastePaperHeadVO(wastepaperhead);
					java.text.DecimalFormat   df3   =new   java.text.DecimalFormat("#.000");  //double保留三位小数
					//净重及主数量
					Double nnum=getUFDouble2(wastepaperhead.getSettlementWeight())-getUFDouble2(wastepaperhead.getcBDehydrantWeight())
							-getUFDouble2(wastepaperhead.getcBDecontaminationWeight());
					wastepaperhead.setNnum(String.valueOf(df3.format(nnum)));
					//更新未检测的检验员、堆号、开包件数、码头、净重、主数量到磅单子表  净重=主数量=本箱货重-本箱扣水分重-本箱扣杂质重
					result=this.paperheadmapper.updatePoundInspector(wastepaperhead);
					//更新磅单主表净重、总包数
					result =this.paperheadmapper.updatePoundbill(wastepaperhead);
				}else if("1".equals(wastepaperhead.getIsCheck()) && "合格".equals(wastepaperhead.getIsQualify())){
					wastepaperhead.setIsCheck("2");//合格的数据直接到已检测里面
					jsonObject=insertNotCheck(wastepaperhead, bodylist);
				}else if("1".equals(wastepaperhead.getIsCheck()) && "不合格".equals(wastepaperhead.getIsQualify())){
					jsonObject=insertNotCheck(wastepaperhead, bodylist);
				}else{
					jsonObject=insertNotCheck(wastepaperhead, bodylist);
				}
			} catch (Exception e) {
				throw new BusinessException("进口废纸操作数据库异常:"+e.getMessage());
			}
		}
		jsonObject.put("success", "success");
		return jsonObject.toString();
	}
	
	/**
	 * 进口数据计算
	 * @param wastepaperhead
	 * @param bodylist
	 * @param type :0代表app提交，1代表iuap修改提交
	 */
	public WastePaperHeadVO caluImportData(int type,WastePaperHeadVO wastepaperhead,List<WastePaperBodyVO> bodylist){
		//1、计算件数 2、总计算件数  3、开包每件重 4、本想箱扣水分重 5、本箱杂志扣重  6、本箱不合格纸重
		if(bodylist!=null && bodylist.size()>0 ){
			Double calPieceNumber=getUFDouble2(0);//计算件数
			Double zkcount=getUFDouble2(0);//杂质不合格件数和扣率汇总【杂质扣率要*100%】
			Double unqualifiedPaperCount=getUFDouble2(0);//不合格纸不合格件数和扣率汇总【不合格纸扣率要*100%】

			Double waterPackage=getUFDouble2(0);//水分不合格件数合计
			Double waterDeductionRate=getUFDouble2(0);//水分不合格扣率合计【水分扣率不用*100%】
			StringBuffer waterReason=new StringBuffer();//水分不合格原因合计 【】【】【】

			Double impurityPackage=getUFDouble2(0);//杂志不合格件数合计
			Double impurityDeductionRate=getUFDouble2(0);//杂志不合格扣率合计
			StringBuffer impurityReason=new StringBuffer();//杂志不合格原因合计 【】【】【】

			Double unqualifyPackage=getUFDouble2(0);//不合格纸不合格件数合计
			Double unqualifyDeductionRate=getUFDouble2(0);//不合格纸不合格扣率合计
			StringBuffer unqualifyReason=new StringBuffer();//不合格纸不合格原因合计 【】【】【】

			Double allUnqualifyPackage=getUFDouble2(0);//水分、杂杂、不合格纸不合格件数合计
			//件数
			for(int i=0;i<bodylist.size();i++){
				WastePaperBodyVO bodyvo=bodylist.get(i);
				if(bodyvo.getReasonid()!=null && !"".equals(bodyvo.getReasonid())){
					if("1001G410000000000U7K".equals(bodyvo.getReasonid()) || "1001G410000000000U7L".equals(bodyvo.getReasonid()) ){//水分
						if(type==0){//app
							calPieceNumber=calPieceNumber+getUFDouble2(100/(100-getUFDouble2(bodyvo.getDeductionRate()))*getUFDouble2(bodyvo.getPackageNo()));
							waterPackage=waterPackage+getUFDouble2(bodyvo.getPackageNo());
							waterDeductionRate=waterDeductionRate+getUFDouble2(bodyvo.getDeductionRate());
							waterReason.append("【"+bodyvo.getReason()+"】");
							allUnqualifyPackage=allUnqualifyPackage+getUFDouble2(bodyvo.getPackageNo());
						}else if(type==1){//iuap
							calPieceNumber=calPieceNumber+getUFDouble2(100/(100-getUFDouble2(bodyvo.getAudit_deductionRate()))*getUFDouble2(bodyvo.getAudit_packageNo()));
							waterPackage=waterPackage+getUFDouble2(bodyvo.getAudit_packageNo());
							waterDeductionRate=waterDeductionRate+getUFDouble2(bodyvo.getAudit_deductionRate());
							waterReason.append("【"+bodyvo.getReason()+"】");
							allUnqualifyPackage=allUnqualifyPackage+getUFDouble2(bodyvo.getAudit_packageNo());
						}
						
					}else if("1001G410000000000U7M".equals(bodyvo.getReasonid())
							|| "1001G410000000000U7N".equals(bodyvo.getReasonid()) || "1001G410000000000U7O".equals(bodyvo.getReasonid()) 
							|| "1001G410000000000U7Q".equals(bodyvo.getReasonid()) || "1001G410000000000U7R".equals(bodyvo.getReasonid())){//杂质
						if(type==0){//app
							zkcount=zkcount+(getUFDouble2(bodyvo.getDeductionRate())*getUFDouble2(bodyvo.getPackageNo())*0.01);//TotalDeductionRate:件数*扣率*0.01
							impurityPackage=impurityPackage+getUFDouble2(bodyvo.getPackageNo());
							impurityDeductionRate=impurityDeductionRate+getUFDouble2(bodyvo.getDeductionRate());
							impurityReason.append("【"+bodyvo.getReason()+"】");
							allUnqualifyPackage=allUnqualifyPackage+getUFDouble2(bodyvo.getPackageNo());
						}else if(type==1){//iuap
							zkcount=zkcount+(getUFDouble2(bodyvo.getAudit_deductionRate())*getUFDouble2(bodyvo.getAudit_packageNo())*0.01);//TotalDeductionRate:件数*扣率*0.01
							impurityPackage=impurityPackage+getUFDouble2(bodyvo.getAudit_packageNo());
							impurityDeductionRate=impurityDeductionRate+getUFDouble2(bodyvo.getAudit_deductionRate());
							impurityReason.append("【"+bodyvo.getReason()+"】");
							allUnqualifyPackage=allUnqualifyPackage+getUFDouble2(bodyvo.getAudit_packageNo());
						}
							
					}else if("1001G410000000000U7S".equals(bodyvo.getReasonid()) || "1001G410000000000U7T".equals(bodyvo.getReasonid())
							|| "1001G410000000000U7U".equals(bodyvo.getReasonid()) || "1001G410000000000U7V".equals(bodyvo.getReasonid())
							|| "1001G410000000000U7W".equals(bodyvo.getReasonid()) || "1001G410000000000U7X".equals(bodyvo.getReasonid())){//不合格纸
						if(type==0){//app
							unqualifiedPaperCount=unqualifiedPaperCount+(getUFDouble2(bodyvo.getDeductionRate())*getUFDouble2(bodyvo.getPackageNo())*0.01);//TotalDeductionRate:件数*扣率*0.01								
							unqualifyPackage=unqualifyPackage+getUFDouble2(bodyvo.getPackageNo());
							unqualifyDeductionRate=unqualifyDeductionRate+getUFDouble2(bodyvo.getDeductionRate());
							unqualifyReason.append("【"+bodyvo.getReason()+"】");
							allUnqualifyPackage=allUnqualifyPackage+getUFDouble2(bodyvo.getPackageNo());
						}else if(type==1){//iuap
							unqualifiedPaperCount=unqualifiedPaperCount+(getUFDouble2(bodyvo.getAudit_deductionRate())*getUFDouble2(bodyvo.getAudit_packageNo())*0.01);//TotalDeductionRate:件数*扣率*0.01								
							unqualifyPackage=unqualifyPackage+getUFDouble2(bodyvo.getAudit_packageNo());
							unqualifyDeductionRate=unqualifyDeductionRate+getUFDouble2(bodyvo.getAudit_deductionRate());
							unqualifyReason.append("【"+bodyvo.getAudit_reason()+"】");
							allUnqualifyPackage=allUnqualifyPackage+getUFDouble2(bodyvo.getAudit_packageNo());
						}
					}
				}
			}
			java.text.DecimalFormat   df3   =new   java.text.DecimalFormat("#.000");  //double保留三位小数
			wastepaperhead.setCalPieceNumber(Double.valueOf(df3.format(calPieceNumber)));//计算件数
			Double totcalPieceNumber=calPieceNumber+(getUFDouble2(wastepaperhead.getTotalPackageNo())-waterPackage);//总计算件数
			wastepaperhead.setTotcalPieceNumber(Double.valueOf(df3.format(totcalPieceNumber)));
			Double unboxWeightPerPiece=getUFDouble2(0);
			if(getUFDouble2(0).compareTo(totcalPieceNumber)!=0 && (!"~".equals(wastepaperhead.getSettlementWeight()) || !"".equals(wastepaperhead.getSettlementWeight()))){
				unboxWeightPerPiece=getUFDouble2(wastepaperhead.getSettlementWeight())/totcalPieceNumber;//干包每件重
				wastepaperhead.setUnboxWeightPerPiece(Double.valueOf(df3.format(unboxWeightPerPiece)));
			}
			Double cBDehydrantWeight=getUFDouble2(wastepaperhead.getSettlementWeight())-getUFDouble2(wastepaperhead.getTotalPackageNo())* unboxWeightPerPiece;//本箱扣水分重
			wastepaperhead.setcBDehydrantWeight(Double.valueOf(df3.format(cBDehydrantWeight)));
			if(getUFDouble2(0).compareTo(getUFDouble2(wastepaperhead.getTotalPackageNo()))!=0 && (!"~".equals(wastepaperhead.getSettlementWeight()) || !"".equals(wastepaperhead.getSettlementWeight()))){
				Double cBDecontaminationWeight=( getUFDouble2(wastepaperhead.getSettlementWeight())-Double.valueOf(df3.format(cBDehydrantWeight)))/getUFDouble2(wastepaperhead.getTotalPackageNo())*zkcount; //本箱杂志扣重
				wastepaperhead.setcBDecontaminationWeight(Double.valueOf(df3.format(cBDecontaminationWeight)));	
				Double cBUnqualifiedPaperWeight=( getUFDouble2(wastepaperhead.getSettlementWeight())-Double.valueOf(df3.format(cBDehydrantWeight)))/getUFDouble2(wastepaperhead.getTotalPackageNo())*unqualifiedPaperCount;//本箱不合格纸重
				wastepaperhead.setcBUnqualifiedPaperWeight(Double.valueOf(df3.format(cBUnqualifiedPaperWeight)));
			}

			wastepaperhead.setWaterPackage(String.valueOf(waterPackage));
			wastepaperhead.setWaterDeductionRate(String.valueOf(waterDeductionRate));
			wastepaperhead.setWaterReason(String.valueOf(waterReason));
			wastepaperhead.setImpurityPackage(String.valueOf(impurityPackage));
			wastepaperhead.setImpurityDeductionRate(String.valueOf(impurityDeductionRate));
			wastepaperhead.setImpurityReason(String.valueOf(impurityReason));
			wastepaperhead.setUnqualifyPackage(String.valueOf(unqualifyPackage));
			wastepaperhead.setUnqualifyDeductionRate(String.valueOf(unqualifyDeductionRate));
			wastepaperhead.setUnqualifyReason(String.valueOf(unqualifyReason));
			wastepaperhead.setAllUnqualifyPackage(String.valueOf(allUnqualifyPackage));
		}
		return wastepaperhead;
	}
	
	/**
	 * 
	 * @param num
	 * @return
	 */
	public Double getUFDouble2(Object num){
		if(num==null){
			num=0;
		}
		return new Double(num.toString());
	}
	
	/**
	 * 插入未检测提交过来的数据
	 */
	public JSONObject insertNotCheck(WastePaperHeadVO wastepaperhead,List<WastePaperBodyVO> bodylist){
		int result=0;
		JSONObject jsonObject=new JSONObject();
		int headlength  =this.paperheadmapper.insertWastePaperHeadVO(wastepaperhead);
		if(bodylist!=null && bodylist.size()>0 && headlength>0){
			result=this.bodyservice.insertPaperBody(bodylist);
			jsonObject.put("message", "新增进口废纸检测主表成功："+headlength+"条，子表成功："+result+"条");
		}
		//更新未检测的检验员、堆号、开包件数、码头到磅单
		result=this.paperheadmapper.updatePoundInspector(wastepaperhead);
		return jsonObject;
	}
	
	public List<WastePaperHeadVO> queryPaperHeadVO(Map<String, Object> map){
		List<WastePaperHeadVO> headvolist=this.paperheadmapper.queryWastePaperHeadVO(map);
		return headvolist;
	}
	
	
	@Override
	protected ServiceFeature[] getFeats() {
		return new ServiceFeature[0];
	}

	public int rangeweight(String poundNo, String weightData) {
		int result=this.paperheadmapper.rangeweight(poundNo,weightData);
		return result;
	}
	/**
	 * 更新iuap进口废纸
	 * @param headvo
	 * @return
	 */
	//事务回滚
	@Transactional
	public int updateWasterPaper(WastePaperHeadVO headvo) {
		int result=0;
		if(headvo.getId()!=null){
			//进口计算数据
			headvo =caluImportData(1,headvo,headvo.getBodylist());
			result=this.paperheadmapper.updateHeadvo(headvo);
			java.text.DecimalFormat   df3   =new   java.text.DecimalFormat("#.000");  //double保留三位小数
			//净重及主数量
			Double nnum=getUFDouble2(df3.format(headvo.getSettlementWeight()))-getUFDouble2(df3.format(headvo.getcBDehydrantWeight()==null?new Double(0):headvo.getcBDehydrantWeight()))
					-getUFDouble2(headvo.getcBDecontaminationWeight()==null?new Double(0):headvo.getcBDecontaminationWeight());
			headvo.setNnum(String.valueOf(df3.format(nnum)));
			//更新总包数、净重、主数量  净重=主数量=本箱货重-本箱扣水分重-本箱扣杂质重
			this.paperheadmapper.updatePoundbill(headvo);
			//更新磅单子表主数量
			this.paperheadmapper.updatePoundbill_b(headvo);
		}
		if(headvo.getBodylist()!=null&& headvo.getBodylist().size()>0){
			for(WastePaperBodyVO bodyvo:headvo.getBodylist()){
				if(bodyvo.getId()!=null){
					this.paperbodymapper.updateBodyvo(bodyvo);
				}
			}
		}
		
		//更新图片
		String[] imgUrl = headvo.getImgUrl();
		ArrayList<String> filenames = new ArrayList<String>();
		if(imgUrl!=null && imgUrl.length!=0){
			for (String img : imgUrl) {
				String[] split = img.split("/");
				String filen = split[split.length-1];
				filenames.add(filen);
			}
		}
		String[] array = filenames.toArray(imgUrl!=null?imgUrl:new String[0]);
		String filenamewher = "'"+StringUtils.join(array,"','")+"'";
		headvo.setImgUrls(filenamewher);
		int delFileUrl = this.paperheadmapper.delFileUrl(headvo);
		
		return result;
	}

	public boolean queryrangeweightAuthorities(String userName) {
		if(userName!=null){
			String result=this.paperheadmapper.queryrangeweightAuthorities(userName);
			if(result!=null && !"".equals(result)){
				return true;
			}
		}
		return false;
	}

	/**
	 * 进口废纸称重导出
	 * @param jsonArray
	 * @return
	 */
	public ExcelParam download(JSONArray jsonArray,List<WastePaperHeadVO> waslist) {
		List<WastePaperHeadVO> list =null;
		if(jsonArray!=null){
			list = jsonArray.toJavaList(WastePaperHeadVO.class);
		}else{
			list=waslist;
		}
		String[] heads = {"磅单号", "审核状态", "进口明细单号", "车牌号", "箱号", "供应商", "物料品种", "总来数", "实来数", "毛重",
				"皮重", "货重", "扣重", "总件重", "堆号"};
		List<String[]> data = new LinkedList<>();
		for (int i = 0; i < list.size(); i++) {
			WastePaperHeadVO entity = list.get(i);
			String[] temp = new String[heads.length];
			temp[0] = entity.getPoundNo();
			if("Y".equals(entity.getAuditStatus())){
				temp[1] = "已审核";
			}else{
				temp[1] = "未审核";
			}
			temp[2] = entity.getApplicationNo();
			temp[3] = entity.getLicensePlateNo();
			temp[4] = entity.getCaseNo();
			temp[5] = entity.getSupplyUnit();
			
			temp[6] = entity.getMaterialVariety();
			temp[7] = entity.getTotalEntryNo();
			temp[8] = entity.getRealNo();
			temp[9] = String.valueOf(entity.getGrossWeight());
			temp[10] = String.valueOf(entity.getTareWeight());
			temp[11] = String.valueOf(entity.getSettlementWeight());//货重
			temp[12] = entity.getDeductWeight();//扣重
			temp[13] = entity.getTotalPackageNo();//总件重
			temp[14] = entity.getHeapName();//堆号
			
			data.add(temp);
		}
		ExcelParam param = new ExcelParam.Builder("进口导出数据").headers(heads).data(data).build();
		return param;
	}

}
